//
//  FDRefreshControl.swift
//  WeiBoSwift
//
//  Created by Jacky Sun on 16/5/18.
//  Copyright © 2016年 syf. All rights reserved.
//

import UIKit
import SnapKit

class FDRefreshControl: UIRefreshControl {
    
    var scroll: UIScrollView?
    
    /// 箭头的方向默认是true
    var arrowDirection: Bool = true
    /// 圈圈是否在转动
    var cicleISRotating: Bool = false
    
    override init() {
        super.init()
        addSubview(refreshVIew)
        refreshVIew.snp_makeConstraints { (make) in
            make.width.equalTo(170)
            make.height.equalTo(60)
            make.centerX.equalTo(self)
            make.top.equalTo(self)
        }
        
        // 注册kvo监听frame 变化
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.New, context: nil)
            }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
      //  print(self.frame)
        
        //print("正在刷新： \(refreshing)")
        let frameY = frame.origin.y
        if frameY >= 0{
            return
        }
        
        /**
         *  判断是否开启刷新事件
         */
        if refreshing && !cicleISRotating {
          print("开始转圈")
            refreshVIew.startLoading()
            cicleISRotating = true
            return
        }
        
        if frameY <= -50 && arrowDirection {
            print("开始旋转")
          refreshVIew.rotationArrowIMg(arrowDirection)
          arrowDirection = !arrowDirection

        }
        else if frameY > -50 && !arrowDirection {
          print("回复原形")
            refreshVIew.rotationArrowIMg(arrowDirection)
            arrowDirection = !arrowDirection
        }
    }
    
    /**
     重写结束加载方法
     */
    override func endRefreshing() {
        super.endRefreshing()
        
//        self.performSelector(<#T##aSelector: Selector##Selector#>, withObject: <#T##AnyObject?#>, afterDelay: <#T##NSTimeInterval#>)
        NSThread.sleepForTimeInterval(1.0)
        refreshVIew.endLoading()
        cicleISRotating = false
        print("请求有结果了")
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 懒加载
    private lazy var refreshVIew: FDRefreshView = FDRefreshView.shareRefhreshView()

    
    deinit{
        removeObserver(self, forKeyPath: "frame")
    }
}



class FDRefreshView: UIView {
    // 旋转
    @IBOutlet weak var rotationVIew: UIImageView!
    /**
     上层
     */
    @IBOutlet weak var tipView: UIView!
 
    /**
     箭头图标
    */
    @IBOutlet weak var arrowIMg: UIImageView!

    class func shareRefhreshView() ->FDRefreshView{
        return NSBundle.mainBundle().loadNibNamed("FDRefreshView", owner: nil, options: nil).last as! FDRefreshView
    }
    

    /**
     旋转箭头img
     */
    func rotationArrowIMg(arrowDirect: Bool) {
        var angle = M_PI
        angle += arrowDirect ? -0.01 : 0.01
        UIView.animateWithDuration(0.3) {
            self.arrowIMg.transform = CGAffineTransformRotate(self.arrowIMg.transform,CGFloat(angle) )
        }
    }
    
    /**
     开始加载
     */
    func startLoading(){
        
        tipView.hidden = true
       let anim =  CABasicAnimation(keyPath: "transform.rotation")
        anim.duration = 1
        anim.toValue =  M_PI * 2
        anim.repeatCount = MAXFLOAT
        anim.removedOnCompletion = false
        rotationVIew.layer.addAnimation(anim, forKey: nil)
    }
    
    /**
     *  结束加载
     */
    func endLoading(){
        
        tipView.hidden = false
        rotationVIew.layer.removeAllAnimations()
        
    }
    
}
